/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ni;

import java.io.IOException;
import java.net.InetAddress;
import commProtocol.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Marianne Bellanger
 */
public class ClassUDP implements Runnable, Observable_udp{
    private DatagramSocket dtgS;
    private MulticastSocket multiS;
    private ArrayList<Observer_udp> listObserver;

    public ClassUDP() throws SocketException, IOException{
        dtgS = new DatagramSocket(7000);
        multiS = new MulticastSocket(7000);
        listObserver = new ArrayList<Observer_udp>();
    }

    public void SendHelloBye (Message message) throws Exception{
         byte[] tosend;
         DatagramPacket dtgP;

        tosend = Message.toByteArray(message);
        dtgP = new DatagramPacket(tosend, tosend.length);

        multiS.send(dtgP);
    }


    public void SendMessage (Message message, InetAddress address) throws Exception{
         byte[] tosend;
         DatagramPacket dtgP;

        tosend = Message.toByteArray(message);
        dtgP = new DatagramPacket(tosend, tosend.length);

        dtgS.send(dtgP);
    }

    public void addObserver(Observer_udp obs) {
        this.listObserver.add(obs);
    }

    public void notify(Message message) {
        for(Observer_udp obs : this.listObserver )
            obs.update(message);
    }

    public void delObserver(Observer_udp obs) {
        this.listObserver.remove(obs);
    }

    public void run() {
        DatagramPacket dtgPR = null;

        try {
            dtgS.receive(dtgPR);
            Message m = Message.getMessage(dtgPR.getData(), dtgPR.getOffset(), dtgPR.getLength());
            notify(m);

        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ClassUDP.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ClassUDP.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
